package main.java.com.lx.tools.utils

import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.progress.util.ProgressIndicatorUtils
import com.intellij.openapi.project.Project

class PlatformUtil {
    companion object {

        /**
         * 在异步线程池中执行任务，真正的异步任务。不会阻塞主线程
         */
        fun executeBackgroundTask(project: Project, title: String, runnable: Runnable) {
            ApplicationManager.getApplication().invokeLater({
                ApplicationManager.getApplication().runReadAction({
                    object : Task.Backgroundable(project, title) {
                        override fun run(progressIndicator: ProgressIndicator) {
                            ProgressIndicatorUtils.runWithWriteActionPriority({
                                runnable.run()
                                if (!progressIndicator.isCanceled) {
                                    progressIndicator.stop()
                                }
                            }, progressIndicator)
                        }

                        override fun shouldStartInBackground(): Boolean {
                            return true
                        }
                    }.queue()
                })
            })
        }

        /**
         * 通知文件发生变化
         */
        fun notifyFileChanged(project: Project) {
            project.baseDir?.refresh(true, true)
        }

        /**
         * 获取本地存储的key value ，string类型
         */
        fun getData(key: String, defaultValue: String): String {
            return PropertiesComponent.getInstance().getValue(key, defaultValue)
        }

        /**
         * 获取本地存储的key value ，string类型
         */
        fun getData(key: String, defaultValue: Boolean): Boolean {
            return PropertiesComponent.getInstance().getBoolean(key, defaultValue)
        }

        /**
         * 存储key value数据，string类型
         */
        fun setData(key: String, stringValue: String) {
            PropertiesComponent.getInstance().setValue(key, stringValue)
        }

        /**
         * 存储key value数据，boolean类型
         */
        fun setData(key: String, booleanValue: Boolean) {
            PropertiesComponent.getInstance().setValue(key, booleanValue)
        }

    }

}